<template>
  <el-drawer
    :visible.sync="drawerVisible"
    :with-header="false"
    :size="size"
    :before-close="closeDrawer"
  >
    <p class="drawertitle">{{ drawertitle }}</p>
    <div class="form-box">
      <!-- 跳页面 添加 | 编辑 -->
      <el-form
        ref="formData"
        :disabled="disabled"
        label-position="right"
        :model="formData"
        :rules="rules"
      >
        <el-form-item
          v-for="(field, index) in config.fieldsConfig"
          :key="index"
          v-if="field.isShow ? !field.isShow : true"
          :prop="field.name"
          :rules="validateAction(field.rules, field.label)"
          :label="field.label ? `${field.label}：` : null"
          :label-width="field.labelwidth ? `${field.labelwidth}px` : '1.6rem'"
        >
          <template slot="label">
            <span>{{ field.label ? `${field.label}：` : null }}</span>
          </template>
          <component
            :is="field.fieldType"
            :key="index"
            :ref="field.name"
            :label="field.label"
            :render="field.render"
            :value="formDataAction(formData, field.name)"
            :multiple="field.multiple"
            :picker-options="field.pickerOptions"
            :format="field.format"
            :date="field.date"
            :maxlength="field.maxlength"
            :type="field.type"
            :area-length="field.areaLength"
            v-bind="field"
            :options="field.options"
            :optionsurl="field.optionsurl"
            :disabled="field.disabled"
            @input="updateForm"
            @change="changeForm"
          />
        </el-form-item>
        <slot v-for="item in slotForm" :name="item" />
      </el-form>
      <div class="buttom">
        <slot v-if="config['buttons']" name="buttons">
          <el-button :loading="submitLoading" type="primary" @click="submit">{{
            onSubmitText
          }}</el-button>
          <el-button @click="reset">{{ onBackText }}</el-button>
        </slot>
        <slot v-for="item in slotList" :name="item" />
      </div>
    </div>
  </el-drawer>
</template>

<script>
import SelectList from "./basicComponent/SelectList";
import TextInput from "./basicComponent/TextInput";
import Uploads from "./basicComponent/Uploads";
import checkboxTime from "./basicComponent/checkboxTime";
import lableView from "./basicComponent/lableView";
import NumberInput from "./basicComponent/NumberInput";
import RadioBox from "./basicComponent/RadioBox";
import SelectTagView from "./basicComponent/SelectTagView";
import clickLink from "./basicComponent/clickLink";
// import Tinymce from "./basicComponent/Tinymce";
import RadioBoxStyle from "./basicComponent/RadioBoxStyle";
import Cascader from "./basicComponent/Cascader";
import SelectType from "./basicComponent/SelectType";
import TextView from "./basicComponent/TextView";
import DateTimeSelect from "./basicComponent/DateTimeSelect";
import DateTimePicker from "./basicComponent/DateTimePicker";
import VideoUpload from "./basicComponent/VideoUpload";
import APKUpload from "./basicComponent/APKUpload";

import { validateIdCode } from "@/utils/validate.js";
import { formatTimeString } from "@/utils/date.js";
export default {
  name: "FormGenerator",
  components: {
    SelectList,
    TextInput,
    Uploads,
    checkboxTime,
    lableView,
    NumberInput,
    SelectTagView,
    clickLink,
    // Tinymce,
    RadioBox,
    RadioBoxStyle,
    Cascader,
    SelectType,
    TextView,
    DateTimeSelect,
    DateTimePicker,
    VideoUpload,
    APKUpload,
  },
  props: {
    config: {
      type: Object,
      default: () => {},
    },
    value: {
      type: Object,
      default: () => {},
    }, // 按钮的 slot
    slotList: {
      type: Array,
      default: () => [],
    }, // 表单的 slot
    slotForm: {
      type: Array,
      default: () => [],
    },
    cache: {
      type: Boolean,
      default: true,
    },
    dialogVisible: {
      type: Boolean,
      default: true,
    },
    disabled: {
      type: Boolean,
      default: false,
    },
    drawertitle: {
      type: String,
      default: "",
    },
    drawerVisible: {
      type: Boolean,
      default: false,
    },
    rules: {
      type: Object,
      default: () => {},
    },
    size: {
      type: String,
      default: "600px",
    },
  },
  data() {
    return {
      varlast: null, // 控制按钮不能重复点击
      varnow: null, // 控制按钮不能重复点击
      validate: [{ required: true, message: "请输入", trigger: "blur" }],
      formData: this.value,
      onBackShow: this.config.buttons ? this.config.buttons.onBackShow : false,
      onSubmitText: this.config.buttons
        ? this.config.buttons.onSubmitText || "保存"
        : "",
      onBackText: this.config.buttons
        ? this.config.buttons.onBackText || "取消"
        : "",
      onBackAction: this.config.buttons
        ? this.config.buttons.onBackAction
        : false,
      submitLoading: false,
    };
  },
  watch: {
    value(val) {
      this.formData = this.value;
    },
  },
  methods: {
    gotoback() {
      this.$router.go(-1);
    },
    // 返回值
    formDataAction(data, name) {
      const str = name.split(".");
      if (str.length >= 2) {
        return data[str[0]][str[1]];
      } else {
        return data[name];
      }
    },
    NorequiredVal(rule, value, callback) {
      if (value) {
        if (validateIdCode(value)) {
          callback();
        } else {
          callback(new Error("输入的身份证有误！"));
        }
      } else {
        callback();
      }
    },
    requiredVal(rule, value, callback) {
      if (validateIdCode(value)) {
        callback();
      } else {
        callback(new Error("输入的身份证有误！"));
      }
    },
    // 校验规则
    validateAction(val, lable) {
      if (val === "required") {
        return [{ required: true, message: "请输入", trigger: "blur" }];
      }
      if (val === "select") {
        return [
          { required: true, message: "请选择" + lable, trigger: "change" },
        ];
      }
      if (val === "array") {
        return [
          {
            type: "array",
            required: true,
            message: "请选择" + lable,
            trigger: "blur",
          },
        ];
      }
      if (val && val.indexOf("validateIdCode") > -1) {
        if (val.indexOf("required") > -1) {
          return [
            { validator: this.requiredVal, required: true, trigger: "blur" },
          ];
        }
        return [{ validator: this.NorequiredVal, trigger: "blur" }];
      }
      console.log(val);

      if (typeof val == "object") {
        return val;
      }
    },
    updateForm(fieldName, value) {
      const str = fieldName.split(".");
      if (str.length >= 2) {
        this.formData[str[0]][str[1]] = value;
      } else {
        this.formData[fieldName] = value;
      }
    },
    // 设置 确认按钮 添加lodding
    setsubmitLoading(dis) {
      this.submitLoading = dis;
    },
    submit() {
      this.varlast = Date.now();
      this.$refs["formData"].validate((valid) => {
        // 校验通过后  控制3秒后才能再次调用
        if (valid) {
          this.submitLoading = true;
          this.$emit("submit");
          // if (this.varnow) {
          //   if (this.varlast - this.varnow > 2000) {
          //     this.varnow = Date.now()
          //     this.varlast = this.varnow
          //     this.$emit('submit')
          //   }
          // } else {
          //   this.varnow = Date.now()
          //   this.varlast = this.varnow
          //   this.$emit('submit')
          // }
        } else {
          return false;
        }
      });
    },
    closeDrawer() {
      this.submitLoading = false;
      this.reset();
    },
    changeForm(fieldName, value) {
      this.formData[fieldName] = value;
      this.$emit("change");
    },
    reset() {
      this.submitLoading = false;
      this.$emit("update:drawerVisible", false);
      this.$refs["formData"].resetFields();
      for (var name in this.formData) {
        var typeStr = Object.prototype.toString.call(this.formData[name]);
        if (typeStr === "[object Array]") {
          this.formData[name] = [];
        }
        if (typeStr === "[object Object]") {
          this.formData[name] = {};
        }
        if (typeStr === "[object String]") {
          this.formData[name] = null;
        }
      }
    },
  },
};
</script>
<style lang="less" scoped>
::v-deep .el-form-item {
  margin-bottom: 19px;
}
.interForm {
  display: inline-block;
  width: 49%;
  vertical-align: text-top;
}
.moreForm {
  padding: 0 0.3rem 0 0;
  box-sizing: border-box;
}
.lable_Css {
  display: inline-block;
  line-height: 0.18rem;
}
.rules_Css {
  display: inline-block;
  float: right;
  width: 0.9rem;
  line-height: 0.2rem;
}
.form-box {
  padding: 0 0.6rem 0.3rem 0.2rem;
}
</style>
